package de.slothsoft.wasbinich.core.database.webservice;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

import de.slothsoft.wasbinich.core.Picture;
import de.slothsoft.wasbinich.core.WebserviceUrls;
import de.slothsoft.wasbinich.core.database.DatabaseException;
import de.slothsoft.wasbinich.core.database.PictureBean;

public class WebservicePictureBean extends AbstractWebserviceBean implements PictureBean {

    protected static final Gson GSON = new GsonBuilder().registerTypeAdapter(String[].class,
	    new StringArrayTypeAdapter()).create();

    public WebservicePictureBean(RestCommunicator communicator) {
	super(communicator);
    }

    @Override
    public Picture getRandomPicture() throws DatabaseException {
	String json = get(WebserviceUrls.getRandomPictureUrl());
	return getPictureFromString(json);
    }

    protected static Picture getPictureFromString(String json) throws DatabaseException {
	try {
	    return GSON.fromJson(json, Picture.class);
	} catch (JsonSyntaxException e) {
	    System.err.println("Error in WebservicePictureBean.getPictureFromString(): " + json); //$NON-NLS-1$
	    throw e;
	}
    }
}
